//
//  ViewController.swift
//  WebViewContent
//
//  Created by HM on 16/1/1.
//  Copyright © 2016年 TMPercy. All rights reserved.
//

import UIKit
import SafariServices

class ViewController: UITableViewController {

    var sectionTitles = ["Section 1","Section 2"]
    var sectionContent = [["Opening Web Content in Mobile Safari","Loading Web Content Using UIWebView"],["Loading Web Content Using SFSafariViewController","Raywenderlich","apple"]]
    var links = ["https://www.baidu.com","http://www.raywenderlich.com","http://www.apple.com/cn/"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //去掉tableview多余横线
        tableView.tableFooterView = UIView(frame: CGRectZero)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - Table view data source
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 2
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
        return 2
    } else {
        return 3
        }
    }
    
    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionTitles[section]
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath:indexPath)
        cell.textLabel?.text = sectionContent[indexPath.section][indexPath.row]
        return cell
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        switch indexPath.section {
    case 0:
            if indexPath.row == 0{
        if let url = NSURL(string:"http://www.apple.com/itunes/charts/paid-apps/") {
        //safari中打开网页，这一句就搞定了，这时会跳到safari。。。
        UIApplication.sharedApplication().openURL(url)
        }
    } else {
        //如果用web view控件，就不会跳到safari，而是会内置在app里
        performSegueWithIdentifier("showWebView", sender: self)
        }
        
    case 1:
        //safariViewController显示网页
        if let url = NSURL(string: links[indexPath.row]){
            let safariController = SFSafariViewController(URL: url,entersReaderIfAvailable: true)
            presentViewController(safariController, animated: true, completion: nil)
        }
        
    default:
        break
        }
        tableView.deselectRowAtIndexPath(indexPath, animated: false)
    }


}

